#ifndef ZBufferCommon_H
#define ZBufferCommon_H
#include "UnityCG.cginc"

sampler2D _CameraDepthNormalsTexture;
float4 _CameraDepthTexture_ST;

float CheckBounds(float2 uv, float d) {
    float ob = any(uv < 0) + any(uv > 1);
#if defined(UNITY_REVERSED_Z)
    ob += (d <= 0.00001);
#else
    ob += (d >= 0.99999);
#endif
    return ob * 1e8;
}

float SampleDepthNormal(float2 uv, out float3 normal) {
    float4 cdn = tex2D(_CameraDepthNormalsTexture, uv);
    normal = DecodeViewNormalStereo(cdn) * float3(1.0, 1.0, -1.0);
    float d = DecodeFloatRG(cdn.zw);
    return d * _ProjectionParams.z + CheckBounds(uv, d);
}

float GetDepthNormal(float2 uv, out float3 vNorm) {
	float vDepth = SampleDepthNormal(UnityStereoScreenSpaceUVAdjust(uv, _CameraDepthTexture_ST), vNorm);
	vDepth -= _ProjectionParams.z / 65536;
	return vDepth;
}

#endif